package models;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import objects.Constituent;

/* Accessible only through SemRepModel */
class SemRepXMLWriter {
	
	private Constituent con;
	
	public SemRepXMLWriter() {
		con = null;
	}
	
	public void write(File file) throws FileNotFoundException, IOException {
		Element theRoot = putXML(con);

		Document doc = new Document(theRoot);
		XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat());
		xmlOutput.output(doc, new FileOutputStream(new File(file.getAbsolutePath())));
	}
	
	public Element putXML(Constituent currentCon) {
		Element theRoot = new Element("constituent");
		
		if(currentCon.getLabel() != null) {
			theRoot.setAttribute("label", currentCon.getLabel());
		}
		
		if(currentCon.getSense() != null) {
			theRoot.setAttribute("sense", currentCon.getSense());
		}
		
		if(currentCon.getConcept().getName() !=null) {
			theRoot.setAttribute("concept", currentCon.getConcept().getName());
		}
		
		if(currentCon.getTranslation().getName() !=null) {
			theRoot.setAttribute("translation", currentCon.getTranslation().getName());
		}
		
		if(currentCon.getFeatures() != null && currentCon.getFeatures().getFeatureList().size() > 0) {
			Element features = new Element("features");
			
			for(int i = 0; i < currentCon.getFeatures().getFeatureList().size(); i++) {
				Element feature = new Element("feature");
				
				if(currentCon.getFeatures().getFeatureList().get(i).getName()!= null && currentCon.getFeatures().getFeatureList().get(i).getValue()!=null) {
					feature.setAttribute("name", currentCon.getFeatures().getFeatureList().get(i).getName());
					feature.setAttribute("value", currentCon.getFeatures().getFeatureList().get(i).getValue());
					features.addContent(feature);
				}
			}
			
			theRoot.addContent(features);
		}
		
		if(currentCon.getConstituentList()!=null) {
			for(int i = 0; i < currentCon.getConstituentList().size(); i++) {
				theRoot.addContent(putXML(currentCon.getConstituentList().get(i)));
			}
		}
		
		return theRoot;
	}
	
	public void setConstituent(Constituent con) {
		this.con = con;
	}
	
}
